package com.yuan.service.autofetch.impl;

import static com.yuan.common.constant.YuanConstant.FETCHED_FLAG;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yuan.dao.autofetch.AutoFetchDao;
import com.yuan.dao.goods.GoodsDao;
import com.yuan.fetch.AutoFetch;
import com.yuan.goods.Goods;
import com.yuan.service.autofetch.AutoFetchService;
import com.yuan.service.fetchStrategy.FetchStrategyContext;

@Transactional
// 默认抛出RuntimeException时，RollBack
public class AutoFetchServiceImpl implements AutoFetchService {

	private static Logger logger = Logger.getLogger(AutoFetchServiceImpl.class);

	private AutoFetchDao autoFetchDao;

	private GoodsDao goodsDao;

	public void runFetch(AutoFetch autoFetch) {

		try {
			// 更新状态
			autoFetchDao.updateStatus(autoFetch.getId(), FETCHED_FLAG);

			FetchStrategyContext fetchStrategyContext = new FetchStrategyContext(autoFetch.getFetchType());

			List<Goods> goodes = fetchStrategyContext.run(autoFetch.getFetchUrl());

			if(goodes ==null || goodes.isEmpty()){
				return;
			}
			
			goodsDao.save(goodes);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	// 声明为不支持事务
	public List<AutoFetch> readNeedFetch(String ownSign, int fetchNum, int queueNum, String condition) {
		return autoFetchDao.readNeedFetch(ownSign, fetchNum, queueNum, condition);
	}

	@Transactional(rollbackFor = RuntimeException.class)
	public void toInitStatus() {
		autoFetchDao.updateAllStatus(!FETCHED_FLAG);
	}

	public AutoFetchDao getAutoFetchDao() {
		return autoFetchDao;
	}

	public void setAutoFetchDao(AutoFetchDao autoFetchDao) {
		this.autoFetchDao = autoFetchDao;
	}

	public GoodsDao getGoodsDao() {
		return goodsDao;
	}

	public void setGoodsDao(GoodsDao goodsDao) {
		this.goodsDao = goodsDao;
	}
	
	
}
